<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\user\Address as UserAddress;

/**
 * 地址管理接口
 */
class Address extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * @Author LK
     * @date: 2023-12-12 
     * @ApiTitle (获取用户收货地址)
     * @ApiMethod (GET)
     * @ApiParams (name="limit", type="integer", required=true, sample="", description="")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */

    public function getUserAddress()
    {
        $param = $this->request->param();
        extract($param);
        $uid = $this->auth->id;
        $data = UserAddress::getUserAddress($uid, $limit ?? 10);
        $this->success('获取成功', $data);
    }
    /**
     * 获取用户默认地址
     *
     * @ApiMethod (GET)
     */
    public function getDefaultAddress()
    {
        $uid = $this->auth->id;
        $list = UserAddress::getDefaultAddress($uid);
        $this->success('获取成功', $list);
    }
    /**
     * 设置用户默认地址
     *
     * @ApiMethod (POST)
     * @param string $id  地址id
     * 
     */
    public function setDefaultAddress()
    {
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        UserAddress::setDefaultAddress($id, $uid);
        $this->success('设置成功');
    }
    /**
     * 添加收货地址
     *
     * @ApiMethod (POST)
     * @param string $contact  收货人
     * @param string $telephone  手机号
     * @param string $province  省
     * @param string $city  市
     * @param string $area  区
     * @param string $address  地址
     * @param string $longitude  经度
     * @param string $latitude  纬度
     * @param string $is_default  纬度
     * 
     */
    public function addAddress()
    {
        $post = $this->request->post();
        $validate = validate('user.Address'); //使用助手函数
        $result = $validate->check($post);
        if (!$result) {
            $this->error($validate->getError());
        }
        $post['user_id'] = $this->auth->id;
        $res = UserAddress::AddAddress($post);
        if ($res !== false) {
            $this->success('提交成功', $res);
        }
        $this->error('提交失败');
    }
    /**
     * 删除用户收货地址
     *
     * @ApiMethod (POST)
     * @param string $id  地址id
     * 
     */
    public function delAddress()
    {
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $data = UserAddress::get($id);
        $data->delete();
        $this->success('删除成功', $data);
    }
}
